from django.shortcuts import render, HttpResponse, redirect

from stu_exam_manage.models import UserInfo
from .forms import UserForm, RegisterForm
from .forms import College_ClassForm
from .forms import CourseForm

import random

# 预定义code
#     200  正常
#     201  注册成功
#
#     100  登陆失败

# Create your views here.
def login(request):
    ''' 登录 '''
    status = {'code': 200, 'msg': 'success'}
    if request.method == 'GET':
        userform = UserForm()

        if request.GET.get('code', 0) == '201':
            status = {'code':201, 'msg':'注册成功'}
        return render(request, 'user_verify/login.html', locals())
    else:
        userform = UserForm(request.POST)
        if userform.is_valid():
            loginData = userform.cleaned_data
            user_login_info = UserInfo.objects.filter(username=loginData.get('uname'), password=loginData.get('upwd'))
            print('user_login_info:', user_login_info)  # 110
            if user_login_info:
                request.session['userid'] = user_login_info[0].id
                request.session['username'] = user_login_info[0].username
                request.session['classsid'] = user_login_info[0].classs_id
                request.session['courseid'] = user_login_info[0].course_id
                print(request.session)  # 110
                return redirect('/stu_exam_manage/base.html')
            else:
                status['code'] = 100
                status['msg'] = '用户名或密码错误'
                return render(request, 'user_verify/login.html', locals())
        else:
            return render(request, 'user_verify/login.html', locals())


def logout(request):
    ''' 登出 '''
    status = {'code': 200, 'msg': 'success'}
    request.session.flush()      # 删除session
    return redirect('/user_verify/login.html')


def regist(request):
    ''' 注册 '''
    if request.method == 'GET':
        registerform = RegisterForm()
        # college_classform = College_ClassForm()
        courseform = CourseForm()
        return render(request, 'user_verify/register.html', locals())
    else:
        registerform = RegisterForm(request.POST)
        # college_classform = College_ClassForm(request.POST)
        courseform = CourseForm(request.POST)

        if registerform.is_valid() and courseform.is_valid():
            registerData = registerform.cleaned_data
            courseData = courseform.cleaned_data

            registerDataDict = {
                'course_id': courseData.get('name', 1),
                'name': '临时用户' + str(random.random()),
                'username': registerData.get('uname'),
                'password': registerData.get('upwd'),
            }
            print(registerDataDict)
            UserInfo.objects.create(**registerDataDict)
            return  redirect('/user_verify/login.html?code=201')

        else:
            return render(request, 'user_verify/register.html', locals())


